package com.boot.redis.redis.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;

/**
 * redis分布式锁
 */
@RestController
public class GoodController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${server.port}")
    private String serverPort;

    @Autowired
    Redisson redisson;

   final String REDIS_LOCK = "REDIS_LOCK";

    /**
     * 单机版
     */
    @GetMapping("/buy_Goods")
    public String buy_Goods(){
        synchronized (this){
            //看库存够不够
            String resilt = stringRedisTemplate.opsForValue().get("goods:001");
            int number =resilt==null?0:Integer.parseInt(resilt);
            if(number>0){
                int realNumber=number-1;
                stringRedisTemplate.opsForValue().set("goods:001",String.valueOf(realNumber));
                System.out.println("库存还剩下:"+realNumber+"个"+"服务端接口："+serverPort);
                return "库存还剩下:"+realNumber+"个"+"服务端接口："+serverPort;
            }else {
                return "商品已经卖完"+"服务端接口："+serverPort;
            }
        }
    }

    /**
     * redisson分布式版
     */
    @GetMapping("/redissonGoodsfbs")
    public String redissonGoodsfbs() throws Exception {
        String uuid=UUID.randomUUID().toString()+Thread.currentThread().getName();
        RLock lock = redisson.getLock(REDIS_LOCK);
        lock.lock();
        try {
            //看库存够不够
            String resilt = stringRedisTemplate.opsForValue().get("goods:001").toString();
            int number =resilt==null? 0 :Integer.parseInt(resilt);
            if(number>0){
                int realNumber=number-1;
                stringRedisTemplate.opsForValue().set("goods:001",String.valueOf(realNumber));
                System.out.println("库存还剩下:"+realNumber+"个"+"服务端接口："+serverPort);
                return "库存还剩下:"+realNumber+"个"+"服务端接口："+serverPort;
            }else {
                return "商品已经卖完"+"服务端接口："+serverPort;
            }
        } finally {
            //判断是否在锁定状态   //是否是这个线程所持有的
          if(lock.isLocked() && lock.isHeldByCurrentThread()){
              lock.unlock();
          }
        }
    }
}
